package network2;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Font;

public class SingleChatClient extends JFrame implements Runnable{

	Socket socket = null;
	BufferedReader receive = null;
	BufferedWriter send = null;
	boolean threadFlag = true;
	StringBuilder data = new StringBuilder();
	int port = 4444;
	
	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JButton btnConnect;
	private JButton btnDisconnect;
	private JButton btnSend;
	private JTextField message;
	private JScrollPane scrollPane;
	private JTextPane result;
	private JTextField serverIP;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SingleChatClient frame = new SingleChatClient();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public SingleChatClient() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				serverDisconnect();
			}
		});
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 498, 456);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getPanel_1(), BorderLayout.SOUTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);
		
		try{
			InetAddress ia = InetAddress.getLocalHost();
			serverIP.setText(ia.getHostAddress());
			setTitle(ia.getHostAddress());
		}catch(Exception ex){
			ex.printStackTrace();
		}

		
	}

	public void serverConnect(){
		btnConnect.setEnabled(false);
		btnDisconnect.setEnabled(true);
		dataSet("<b>서버에 접속중....</b>");
		Thread t = new Thread(this);
		t.start();
		
	}
	public void serverDisconnect(){
		sendMsg("\tkill");
	}
	public void sendMsg(String str){
		try{
			send.write(str);
			send.newLine();
			send.flush();
			dataSet("<img src='file:\\P:\\workspace\\과정진행\\1403\\1403\\img1.png'><font color='blue'>" + str + "</font>");
		}catch(Exception ex){
			
		}
		
	}
	public void dataSet(String str){
		data.append(str);
		data.append("<br/>");
		result.setText(data.toString());

	}
	@Override
	public void run() {
		try{
			socket = new Socket(serverIP.getText(), port);
			
			OutputStream os = socket.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(os);
			send = new BufferedWriter(osw);
			
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			receive = new BufferedReader(isr);
			
			dataSet("서버에 접속됨");
			threadFlag = true;
			while(threadFlag){
				String str = receive.readLine();
				if(str.equals("\tserverdown")){
					threadFlag = false;
					sendMsg(str);
				}else if(str.equals("\tkill")){
					threadFlag = false;
				}else{
					dataSet("<img src='file:\\P:\\workspace\\과정진행\\1403\\1403\\img2.png'><font color='blue'>" + str + "</font>");
				}
			}
			
			dataSet("<font color='red'>서버가 중지되었습니다.</font>");
			btnConnect.setEnabled(true);
			btnDisconnect.setEnabled(false);
			
			receive.close();
			isr.close();
			is.close();
			
			send.close();
			osw.close();
			os.close();
			
			socket.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.add(getBtnDisconnect());
			panel.add(getServerIP());
			panel.add(getBtnConnect());
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getBtnSend(), BorderLayout.EAST);
			panel_1.add(getMessage(), BorderLayout.CENTER);
		}
		return panel_1;
	}
	private JButton getBtnConnect() {
		if (btnConnect == null) {
			btnConnect = new JButton("서버 접속");
			btnConnect.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					serverConnect();
				}
			});
		}
		return btnConnect;
	}
	private JButton getBtnDisconnect() {
		if (btnDisconnect == null) {
			btnDisconnect = new JButton("접속해제");
			btnDisconnect.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					serverDisconnect();
				}
			});
		}
		return btnDisconnect;
	}
	private JButton getBtnSend() {
		if (btnSend == null) {
			btnSend = new JButton("메시지 전송");
			btnSend.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					String str = message.getText();
					sendMsg(str);
				}
			});
		}
		return btnSend;
	}
	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent ev) {
					if(ev.getKeyCode() == KeyEvent.VK_ENTER){
						String str = message.getText();
						sendMsg(str);
					}
				}
			});
			message.setColumns(10);
		}
		return message;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setFont(new Font("굴림", Font.PLAIN, 16));
			result.setContentType("text/html");
		}
		return result;
	}
	private JTextField getServerIP() {
		if (serverIP == null) {
			serverIP = new JTextField();
			serverIP.setColumns(10);
		}
		return serverIP;
	}
}
